package com.bnzj.core.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * @author barry
 * @date 2019-10-16
 */
@Slf4j
public class DBUtils {
    
    public static Connection getConnection() throws SQLException{
        DataSource dataSource = SpringUtils.get("dataSource");
        return dataSource.getConnection();
    }
    
    public static void close(Connection conn){
        if (conn != null) {
            try {
                if(!conn.isClosed()){
                    conn.close();
                }
            } catch (SQLException e) {
                log.error(e.getMessage());
            }
        }
    }
    
    public static void close(Statement statement){
        if (statement != null) {
            Connection conn = null;
            try {
                if(!statement.isClosed()){
                    conn = statement.getConnection();
                    statement.close();
                }
            } catch (SQLException e) {
                log.error(e.getMessage());
            }
            close(conn);
        }
    }
    
    public static void close(ResultSet resultSet){
        if (resultSet != null) {
            Statement statement = null;
            try {
                if(!resultSet.isClosed()){
                    statement = resultSet.getStatement();
                    resultSet.close();
                }
            } catch (SQLException e) {
                log.error(e.getMessage());
            }
            close(statement);
        }
    }
    
    public static void close(ResultSet resultSet, Statement statement, Connection conn){
        if (resultSet != null) {
            close(resultSet);
        } else if (statement != null) {
            close(statement);
        } else if (conn != null) {
            close(conn);
        }
    }
}
